package com.example.parser;

import org.json.JSONArray;
import org.json.JSONObject;

import com.example.model.ContactListModel;
import com.example.model.ContactModel;




public class ParserGetContact extends ParserBase
{
	private PrsGetContactDelegate delegate;
	
	public interface PrsGetContactDelegate {
		void GetItemInfoParserDidFinish(ParserGetContact parser, Object model);

		void GetItemInfoParserDidFinishEachItem(ParserGetContact parser,
				Object model);

		void GetItemInfoParserDidFail(ParserGetContact parser,
				String errorMessage);
	}
	
	
	public void setDelegate(PrsGetContactDelegate delegate) {
		this.delegate = delegate;
	}
	public ParserGetContact() {
	}
	public ParserGetContact(String data) {
		parseASYNC(data);
	}
	
	void parseSYNC(Object data) {
		if (isProcessing)
			cancle();
		int PROCESSING_TAG = CURENT_PROCESS_TAG;
		while (isProcessing) {
		}
		;
		isProcessing = true;
		
		ContactListModel model = new ContactListModel();
		
		boolean errFlg = false;
		try {
			
//			System.out.println("string " + new String((byte[]) data));

			JSONObject jObject = new JSONObject(new String((byte[]) data));
			
			// status
			
			if(!jObject.isNull("contacts"))
			{
				JSONArray arr = jObject.getJSONArray("contact");
				for(int i=0;i<arr.length();i++)
				{
					JSONObject c = arr.getJSONObject(i);
					
					final ContactModel con = new ContactModel();
					con.setName(!c.isNull("name")?c.getString("name"):"");
					con.setEmail(!c.isNull("email")?c.getString("email"):"");
					con.setBirthday(!c.isNull("birthday")?c.getString("birthday"):"");
					con.setNumber(!c.isNull("number")?c.getString("number"):"");
					model.addItem(con);
				}
			}
			
			
			if (delegate != null && isProcessing && !errFlg
					&& checkIsCurrentTag(PROCESSING_TAG))
				delegate.GetItemInfoParserDidFinish(this, model);

		} catch (Throwable t) {
			t.printStackTrace();
			if (delegate != null && isProcessing
					&& checkIsCurrentTag(PROCESSING_TAG))
				delegate.GetItemInfoParserDidFail(this, "Error khi parser");// message
		}
		
		isProcessing = false;
	}

	public void parseASYNC(final Object data) {
		prsThread = new Thread(new Runnable() {
			public void run() {
				parseSYNC(data);
			}
		});
		prsThread.start();
	}
}